﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpHsql;
using SharpHsql.Data;

namespace SharpHSQL.Test {
    class Helper {
        Database db = DatabaseController.GetDatabase(".");
        Channel channel;

        public Helper() {
            channel = db.Connect("sa", "");
        }
        const int PRODUCTCOUNT = 1001;
        const int ORDERCOUNT = 101 ;
        const int CATEGORYCOUNT = 21;

        public void Init() {
            string script;
            var rd = new Random();
            Result rs;
            for (int i = 1; i < PRODUCTCOUNT; i++) {
                script = string.Format("Insert Into Product Values( {0} ,'Product_{1}',{2},{3} )", i, i, rd.Next(1, CATEGORYCOUNT), rd.Next(10, 1000) / 100);
                rs = db.Execute(script, channel);
                if (rs.Error != null)
                    Console.WriteLine(rs.Error);
            }

            for (int i = 1; i < ORDERCOUNT; i++) {
                script = string.Format("Insert Into Orders Values( {0} ,'{1}',{2} )", i, DateTime.Now, rd.Next(1, ORDERCOUNT-1));
                rs = db.Execute(script, channel);
                if (rs.Error != null)
                    Console.WriteLine(rs.Error);
            }

            for (int i = 1; i < CATEGORYCOUNT; i++) {
                script = string.Format("Insert Into Category Values( {0} ,'Category_{0}')", i);
                rs = db.Execute(script, channel);
                if (rs.Error != null)
                    Console.WriteLine(rs.Error);
            }

            for (int i = 1; i < 50001; i++) {
                script = string.Format("Insert Into OrderDetails Values( {0} ,{1},{2},{3} )", i, rd.Next(1, PRODUCTCOUNT), rd.Next(1, ORDERCOUNT), rd.Next(2, 10));
                rs = db.Execute(script, channel);
                if (rs.Error != null)
                    Console.WriteLine(rs.Error);
            }
        }

        public void CreateIndex() {
            var query = "CREATE INDEX iProduct ON Product(CategoryId)";
            var rs = db.Execute(query, channel);
            if (rs.Error != null)
                Console.WriteLine(rs.Error);


            query = "CREATE INDEX iOrderId ON OrderDetails(OrderId)";
            rs = db.Execute(query, channel);
            if (rs.Error != null)
                Console.WriteLine(rs.Error);

            query = "CREATE INDEX iProductId ON OrderDetails(ProductId)";
            rs = db.Execute(query, channel);
            if (rs.Error != null)
                Console.WriteLine(rs.Error);
        }

        public Result Excute(string script) {
            var rs = db.Execute(script, channel);
            if (rs.Error != null)
                throw new Exception(rs.Error);
            return rs;
        }
    }
}
